import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageWarehousOrderService } from '../../xstorage-manage-services/storage-warehous-order.service';

@Component({
  selector: 'app-storage-warehous-handle',
  templateUrl: './storage-warehous-handle.component.html',
  styleUrls: ['./storage-warehous-handle.component.scss']
})
export class StorageWarehousHandleComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {};
  warehousTableData: Array<any> = [];

  putTypeOptions: any[] = []; // 入库类型Option
  locationOptions: any[] = []; // 库位Option
  warehouseOptions: any[] = []; // 入库仓库
  supplierOptions: any[] = []; // 供应商

  editGoodsItem: any = {};
  /**
   * SN信息 Modal
   * ---------------------------------------------------------------- 
   */
  isSninfoVisible = false;
  setSnData: any[] = [];
  subSnLoading = false;

  /**
   * 快速录入 Modal
   * ---------------------------------------------------------------- 
   */
  isFastVisible = false;
  fastTextareaVal: string = '';

  /**
   * 多库位 Modal
   * ---------------------------------------------------------------- 
   */
  isMoreLocationVisible = false;
  setLocationData: any[] = [];

  submitLoading = false;

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageWarehousOrderService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadPutTypeOptions();
    this.loadWarehouseOptions();
    this.loadSupplierList();

    this.loadDetailData();
  }

  // 入库类型options
  async loadPutTypeOptions() {
    const res: any = await this.commonService.getDictList('inbound_type');
    this.putTypeOptions = res || [];
  }

  // 查询仓库Options
  async loadWarehouseOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  // 查询库位Options
  async loadLocationOptions() {
    let params = {
      whId: !this.commonService.isEmpty(this.detailsData.whPutId) ? this.detailsData.whPutId : '',
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getLocationList(params);
    if (code === 0) {
      this.locationOptions = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res || [];
  }

  async loadDetailData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getWarehousingDetails(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const {list, warehousing} = data || {};

      this.detailsData = warehousing || {};
      this.warehousTableData = list || [];
      this.loadLocationOptions();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * SN信息 Modal
   * ----------------------------------------------------------------
   */
  showSnInfoModal(item: any) {
    this.editGoodsItem = item;
    this.setSnData = item.itemSns ? JSON.parse(item.itemSns) : [];
    this.isSninfoVisible = true;
  }

  addSnLineData() {
    this.setSnData = [
      ...this.setSnData,
      {
        libraryId: '',
        code: '',
        name: ''
      }
    ];
  }

  deleteSnItem(index: number) {
    this.setSnData = this.setSnData.filter((tag: any, i: number) => i !== index);
  }

  locationChange(val: any, index: number, arrs: any[]) {
    let tempObj = this.locationOptions.find(item => item.id === val);
    arrs[index].name = tempObj?.name || '';
  }

  thQuickChange(item: any) {
    if (this.setSnData.length) {
      this.setSnData.map(ele => {
        ele.libraryId = item.id,
        ele.name = item.name
      })
    }
  }

  async submitSnInfoData() {
    if (!this.setSnData.length) {
      this.msg.warning('请先添加SN信息');
      return
    }

    let flArrs = this.setSnData.filter(m => !this.commonService.isEmpty(m.libraryId) || !this.commonService.isEmpty(m.code));
    if (flArrs.length) {
      // 库位不可重复
      // let repeatArrs: any[] = [];
      // let repeatNum: number = 0;
      // flArrs.forEach((ele: any) => {
      //   if (!this.commonService.isEmpty(ele.name)) {
      //     if (repeatArrs.includes(ele.name)) {
      //       repeatNum += 1;
      //     } else {
      //       repeatArrs.push(ele.name);
      //     }
      //   }
      // })
      // if (repeatNum > 0) {
      //   this.msg.warning('库位不可重复');
      //   return
      // }

      // 两者其中之一不为空，提示
      let isEmptyKw = flArrs.some(m => this.commonService.isEmpty(m.libraryId));
      let isEmptyCode = flArrs.some(m => this.commonService.isEmpty(m.code));
      if (isEmptyKw) {
        this.msg.warning('库位不能为空');
        return
      } else if (isEmptyCode) {
        this.msg.warning('SN码不能为空');
        return
      }
    }

    // 库位和SN都是空的数据 不添加
    let subArr = this.setSnData.filter(item => !this.commonService.isEmpty(item.libraryId) && !this.commonService.isEmpty(item.code));
    if (!subArr.length) {
      this.msg.warning('所提交数据暂未填写');
      return
    }

    /**
     * SN码 重复验证 STRAT
     * -------------------------------------------------------------------------------------------------------- */

    // SN码相同不可提交(modal 输入内容验证)
    let contrastArrs = this.setSnData.map(m => m.code);
    let resultStr = this.searchKeys(contrastArrs);
    if (!this.commonService.isEmpty(resultStr)) {
      this.msg.warning(resultStr);
      return
    }

    // SN码相同不可提交(入库明细列表 内容验证 **不同品牌才可添加相同SN码)
    let detailedContrastArrs = this.warehousTableData.filter(el => !this.commonService.isEmpty(el.itemSns) && (el.whGoodsCode !== this.editGoodsItem.whGoodsCode));
    let newArrs = Array.from(new Set(this.setSnData.map(m => m.code)));
    let conmStr = '';

    if (detailedContrastArrs.length) {
      detailedContrastArrs.forEach((item: any) => {
        let sbSnArrs = JSON.parse(item.itemSns);
        sbSnArrs.forEach((tag: any) => {
          // 相同品牌不可有重复SN码
          if (this.editGoodsItem.whGoodsBrandId === item.whGoodsBrandId && newArrs.includes(tag.code)) {
            conmStr += `SN码 ${tag.code} 已存在于商品 ${item.whGoodsName}（${item.whGoodsCode}）中，请检查；`;
          }
        })
      })
    }
    if (!this.commonService.isEmpty(conmStr)) {
      this.msg.warning(conmStr);
      return
    }

    /**
     * SN码 重复验证 END
     * -------------------------------------------------------------------------------------------------------- */

    let params: any = {
      id: this.editGoodsItem.whGoodsId, // 商品id
      list: subArr // Sn数组
    }
    // return
    this.subSnLoading = true;
    const {code, message}: any = await this.services.judgeSnInfoData(params);
    this.subSnLoading = false;

    if (code === 0) {
      let setIndex = this.warehousTableData.findIndex(item => item.whGoodsId === this.editGoodsItem.whGoodsId);
      this.warehousTableData[setIndex].actualStorageNumber = subArr.length || 0;
      this.warehousTableData[setIndex].itemSns = JSON.stringify(subArr);
      this.isSninfoVisible = false;
    } else {
      this.msg.error(message);
    }
  }

  // 批量录入SN 判断相同项
  searchKeys(arr: any){
    let str = "";
    let list = [];
    for (let i = 0; i < arr.length; i++) {
      let hasRead = false;
      for ( let k = 0; k < list.length; k++) {
        if (list[k] == arr[i]){
          hasRead = true;
        }
      }

      if(!hasRead){
        let _index: any = i + 1;
        let haveSame = false;
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            _index += "," + (j + 1);
            haveSame = true;
          }
        }

        if (haveSame) {
          list.push(arr[i]);
          str += `第 ${_index} 行，重复SN为 ${arr[i]}；`;
        }
      }
    }
    return str
  }

  /**
   * 快速录入 Modal
   * ---------------------------------------------------------------- 
   */
  showFastInputModal() {
    this.fastTextareaVal = '';
    this.isFastVisible = true;
  }

  submitFastValue() {
    let newArrs: any[] = [];
    let nonArrs: string[] = [];
    let hasIds = this.setSnData.map(m => m.libraryId);
    let strArrs = this.fastTextareaVal.trim().split('\n').filter(ele => !this.commonService.isEmpty(ele));

    strArrs.forEach((item: any) => {
      // let tmpArr = item.split(',');
      let locationObj = this.locationOptions.find(tag => tag.name === item);

      // if (this.commonService.isEmpty(locationObj)) {
      //   nonArrs.push(tmpArr[0]);
      // } else {
      //   // 不已存在库位ID，添加
      //   if (!hasIds.includes(locationObj?.id)) {
      //     newArrs.push({
      //       libraryId: locationObj?.id,
      //       name: locationObj?.name,
      //       code: tmpArr[1]
      //     })
      //   }
      // }
      newArrs.push({
        libraryId: '',
        name: locationObj?.name,
        code: item.trim()
      })
    })

    // if (nonArrs.length) {
    //   this.msg.error(`请注意：库位 ${nonArrs.join('、')} 不存在`);
    // }

    this.setSnData = [
      ...this.setSnData,
      ...newArrs
    ];
    this.isFastVisible = false;
  }

  /**
   * 多库位 Modal
   * ---------------------------------------------------------------- 
   */
  showMoreLocationModal(item: any) {
    // if (!this.commonService.isEmpty(item.actualStorageNumber) && Number(item.actualStorageNumber) > 0) {
    //   this.msg.warning('请先清空实际入库数量');
    //   return
    // }

    this.editGoodsItem = item;
    this.setLocationData = item.libraryText ? JSON.parse(item.libraryText) : [];
    this.isMoreLocationVisible = true;
  }

  addLocationLineItem() {
    this.setLocationData = [
      ...this.setLocationData,
      {
        name: '',
        num: ''
      }
    ];
  }

  deleteKwItem(index: number) {
    this.setLocationData = this.setLocationData.filter((d: any, i: number) => i !== index);
  }

  submitSetLocation() { 
    let flArrs = this.setLocationData.filter(m => !this.commonService.isEmpty(m.id) || !this.commonService.isEmpty(m.num));
    if (flArrs.length) {
      // 库位不可重复
      let repeatArrs: any[] = [];
      let repeatNum: number = 0;
      flArrs.forEach((ele: any) => {
        if (!this.commonService.isEmpty(ele.name)) {
          if (repeatArrs.includes(ele.name)) {
            repeatNum += 1;
          } else {
            repeatArrs.push(ele.name);
          }
        }
      })
      if (repeatNum > 0) {
        this.msg.warning('库位不可重复');
        return
      }

      // 两者其中之一不为空，提示
      let isEmptyKw = flArrs.some(m => this.commonService.isEmpty(m.id));
      let isEmptyNum = flArrs.some(m => this.commonService.isEmpty(m.num));
      if (isEmptyKw) {
        this.msg.warning('库位不能为空');
        return
      } else if (isEmptyNum) {
        this.msg.warning('数量不能为空');
        return
      }
    }

    let subArrs = this.setLocationData.filter(item => !this.commonService.isEmpty(item.id) && !this.commonService.isEmpty(item.num));
    if (!subArrs.length) {
      this.msg.warning('所提交数据暂未填写');
      return
    }

    let setIndex = this.warehousTableData.findIndex(item => item.whGoodsId === this.editGoodsItem.whGoodsId);
    this.warehousTableData[setIndex].libraryText = JSON.stringify(subArrs);
    this.warehousTableData[setIndex].actualStorageNumber = subArrs.reduce((total, item) => { return total + (item.num || 0) }, 0);
    this.isMoreLocationVisible = false;
  }

  clearSetLocation() {
    let setIndex = this.warehousTableData.findIndex(item => item.whGoodsId === this.editGoodsItem.whGoodsId);
    this.warehousTableData[setIndex].libraryText = '';
    this.warehousTableData[setIndex].actualStorageNumber = '';
    this.setLocationData = [];
    this.isMoreLocationVisible = false;
  }

  /**
   * 保存 | 暂存
   */
  async submitHandlePut() {
    let tmpArrs = this.warehousTableData.map((item: any) => {
      return {
        planDetailsId: item.planDetailsId,
        purchaseId: item.id, // 采购单ID
        whGoodsId: item.whGoodsId, // 商品ID
        price: item.price || '', // 入库数量
        number: item.number || '', // 入库单价
        purchaseNumber: item.purchaseNumber || 0, // 采购数量
        frozenNumber: item.frozenNumber || 0, // 冻结数量
        stockNumber: item.stockNumber || 0, // 已入库数量
        state: item.lineState, // 状态 0正常(默认) 1已作废
        type: item.type, // 0 指定SN 1SN管控 2多库位 3普通(默认)
        closeRemark: item.closeRemark || '', // 关闭备注
        actualStorageNumber: item.actualStorageNumber || '', // 实际入库数量
        itemSns: ([1, 2].includes(item.type) && item.itemSns) ? item?.itemSns : '', // SN信息
        libraryText: !this.commonService.isEmpty(item.libraryText) ? item?.libraryText : '', // 库位
        libraryId: this.commonService.isEmpty(item.libraryText) ? item.libraryId : '' // 单个库位
      }
    })
    let params = {
      warehousing: {
        id: this.routeParams.id
      },
      list: tmpArrs
    }
    // return
    this.submitLoading = true;
    const {code, message}: any = await this.services.editWarehousOrderData(params, this.routeParams.id ? 1 : 0);
    this.submitLoading = false;

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadDetailData();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 入库完毕
   * ----------------------------------------------------------------
   */
  setActualStorageNum(item: any) {
    if (item.type === 2 && !this.commonService.isEmpty(item.libraryText)) {
      let dkArrs = item.libraryText ? JSON.parse(item.libraryText) : [];
      // 多库位
      return dkArrs.reduce((total: number, item: any) => { return total + (Number(item.num) || 0) }, 0);
    } else {
      return item.actualStorageNumber || '';
    }
  }

  warehousOver() {
    // 实际入库数量 | 入库库位 必填
    // 批量录入SN(type == 1) && 有实际入库数且大于0(actualStorageNumber)
    // 批量入库(type !== 1) && 有实际入库数且大于0(actualStorageNumber) && 批量库位不为空(libraryText) && 单库位不为空(libraryId)
    let isSub = this.warehousTableData.filter(ele => ele.lineState === 0).some(item => {
      return (item.type === 1 && this.commonService.isEmpty(item.itemSns)) ||
             (item.type !== 1 && (this.commonService.isEmpty(item.actualStorageNumber) || item.actualStorageNumber == 0) && this.commonService.isEmpty(item.libraryText) && this.commonService.isEmpty(item.libraryId));
    })
    if (isSub && this.warehousTableData.length) {
      this.msg.warning('实际入库数量、入库库位存在未填写项或实际入库数量存在为0的项');
      return
    }

    let tipNum = 0;
    let tmpArrs = this.warehousTableData.filter(ele => ele.lineState !== 1)
                                        .map(m => {
                                          return {
                                            number: m.number,
                                            actualStorageNumber: this.setActualStorageNum(m)
                                          }
                                        });
    tmpArrs.forEach((item: any) => {
      if (item.number != item.actualStorageNumber) {
        tipNum += 1;
      }
    })
    let tipStr = `${tipNum > 0 ? `有<b>${tipNum}</b>个商品的实际入库数量和预计入库数量不一致，` : ''}确认已入库完毕？该操作不可逆，是否继续？`;

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: tipStr,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ids: [this.routeParams.id],
          state: 4 // 入库完毕
        }
        const res: any = await this.storageCommonService.updateExamineData(params);

        if (res.code === 0) {
          this.msg.success('操作成功');
          this.loadDetailData();
        } else {
          this.msg.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * other
   * ----------------------------------------------------------------
   */

  // 列合计
  calcSumTotal(key: string) {
    let sum = 0;
    const calcArrs = this.warehousTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 行小计
  calcProduct(num: number, price: number) {
    let pTotal = 0;
    pTotal = num * (price ? (Number(price)) : 0);

    return isNaN(pTotal) ? 0 : pTotal;
  }

  /**
   * 小计合计 实际入库 * 单价
   * @returns 
   */
  calcProductTotal() {
    let sum = 0;
    const calcArrs = this.warehousTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + ((item.actualStorageNumber || 0) * (item.price || 0));
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  coprText(str: any) {
    this.commonService.copyStr(str);
  }

  pageBack() {
    history.back();
  }

  // 批量库位
  batchLocationChange(val: any) {
    this.warehousTableData.forEach((item: any) => {
      // 行状态不为作废 | type 不等于 SN管控、多库位
      if (item.lineState !== 1 && ![1, 2].includes(item.type) && this.commonService.isEmpty(item.libraryText)) {
        item.libraryId = val;
      }
    })
  }

  // Input 快捷切换操作(录入SN、多库位 modal使用)
  snCodeKeDowm(e: any, index: number, idstr: string) {
    let evKey = window.event || e;
    if (evKey.keyCode === 13) {
      if (idstr === 'snInput' && index === (this.setSnData.length - 1)) {
        this.addSnLineData();
      }
      if (idstr === 'numInput' && index === (this.setLocationData.length - 1)) {
        this.addLocationLineItem();
      }

      setTimeout(() => {
        let iptDom = document.getElementById(idstr + (index + 1));
        iptDom?.focus();
      })
    }
  }

  libraryTextStr(arrs: any) {
    let sum = 0;
    let tempArrs: any =  arrs ? JSON.parse(arrs) : [];
    if (tempArrs?.length) {
      sum = tempArrs.reduce((total: number, item: any) => {
        return total + (item.num || 0);
      }, 0)

      return `${ tempArrs.length }个库位共${ sum }件`;
    } else {
      return '-';
    }
  }
}
